package com.nebula.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nebula.constant.MessageConstant;
import com.nebula.constant.PasswordConstant;
import com.nebula.constant.StatusConstant;
import com.nebula.context.BaseContext;
import com.nebula.dto.EmployeeDTO;
import com.nebula.dto.EmployeeLoginDTO;
import com.nebula.dto.EmployeePageQueryDTO;
import com.nebula.dto.PasswordEditDTO;
import com.nebula.entity.Employee;
import com.nebula.exception.AccountLockedException;
import com.nebula.exception.AccountNotFoundException;
import com.nebula.exception.PasswordEditFailedException;
import com.nebula.exception.PasswordErrorException;
import com.nebula.mapper.EmployeeMapper;
import com.nebula.result.PageResult;
import com.nebula.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传入的密码进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        employeeMapper.insert(employee);
    }


    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> employeePage = employeeMapper.pageQuery(employeePageQueryDTO);

        return new PageResult(employeePage.getTotal(), employeePage.getResult());
    }

    /**
     * 启用禁用员工账号
     */
    @Override
    public void startOrStop(Integer status, Long id) {

        Employee employee = Employee.builder()
                .status(status).id(id).build();

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("");
        return employee;
    }

    /**
     * 根据id查询员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeMapper.update(employee);
    }

    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Long currentId = BaseContext.getCurrentId();
        Employee employeeOld = employeeMapper.getById(currentId);
        String oldPassword = passwordEditDTO.getOldPassword();

        String oldPasswordMd5 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        if (employeeOld.getPassword().equals(oldPasswordMd5) ){
            String newPassword = passwordEditDTO.getNewPassword();
            String newPasswordMd5 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
            Employee employeeNew = Employee.builder().id(currentId).password(newPasswordMd5).build();
            employeeMapper.update(employeeNew);
        }else {
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }
    }
}
